import $ from 'jquery';
import {getDictionaryList,zuulHost,marketManageServer} from '../api/api.js';

var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = 'yyyy-MM-dd';

function padding(s, len) {
    var len = len - (s + '').length;
    for (var i = 0; i < len; i++) {
        s = '0' + s;
    }
    return s;
};

var util = {
    getQueryStringByName: function (name) {// 根据变量名，获取url中？后面的变量值
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        var context = "";
        if (r != null)
            context = r[2];
        reg = null;
        r = null;
        return context == null || context == "" || context == "undefined" ? "" : context;
    },
    formatDate: {
        format: function (date, pattern) {
            if(typeof(date) == "undefined" || date == undefined || !date || date == ''){return '' }
            pattern = pattern || DEFAULT_PATTERN;
            return pattern.replace(SIGN_REGEXP, function ($0) {
                switch ($0.charAt(0)) {
                    case 'y':
                        return padding(date.getFullYear(), $0.length);
                    case 'M':
                        return padding(date.getMonth() + 1, $0.length);
                    case 'd':
                        return padding(date.getDate(), $0.length);
                    case 'w':
                        return date.getDay() + 1;
                    case 'h':
                        return padding(date.getHours(), $0.length);
                    case 'm':
                        return padding(date.getMinutes(), $0.length);
                    case 's':
                        return padding(date.getSeconds(), $0.length);
                }
            });
        },
        parse: function (dateString, pattern) {
            var matchs1 = pattern.match(SIGN_REGEXP);
            var matchs2 = dateString.match(/(\d)+/g);
            if (matchs1.length == matchs2.length) {
                var _date = new Date(1970, 0, 1);
                for (var i = 0; i < matchs1.length; i++) {
                    var _int = parseInt(matchs2[i]);
                    var sign = matchs1[i];
                    switch (sign.charAt(0)) {
                        case 'y':
                            _date.setFullYear(_int);
                            break;
                        case 'M':
                            _date.setMonth(_int - 1);
                            break;
                        case 'd':
                            _date.setDate(_int);
                            break;
                        case 'h':
                            _date.setHours(_int);
                            break;
                        case 'm':
                            _date.setMinutes(_int);
                            break;
                        case 's':
                            _date.setSeconds(_int);
                            break;
                    }
                }
                return _date;
            }
            return null;
        }
    },
    formatCommDatas(row, column) {//通用 部分字典值 格式化
        let propName = column.property;
        let propVal = row[column.property];
        if (propVal === null || propVal === '') {
            return;
        }
        if (propName == 'isDel') {
            return propVal == 1 ? '是' : propVal == 0 ? '否' : '未知';
        }
        if (propName == 'failRate' || propName == 'successRate' ) {
            return (propVal == null||propVal == undefined || propVal == "undefined") ? propVal : (propVal*100)+"%" ;
        }
        if (propName == 'isOnline') {
            return propVal == 1 ? '是' : propVal == 0 ? '否' : '未知';
        }
        if (propName == 'resultStatus') {
            return propVal == '1' ? '成功' : propVal == '0' ? '失败' : '未知';
        }
        if (propName == 'operateType') {
            return propVal == 1 ? '查询' : propVal == 2 ? '新增' : propVal == 3 ? '修改' : propVal == 4 ? '删除' : '未知';
        }
        if (propName == 'operateResult') {
            return propVal == '1' ? '成功' : propVal == '0' ? '失败' : '未知';
        }
        if (propName.slice(-propName.length) == propName/*||propName == "auditTime"||propName == 'createTime'||propName == 'modifiedTime'||propName == 'invokTime'*/) {
            return (typeof(propVal) == "undefined" || propVal == undefined || !propVal || propVal == '') ? "" : this.formatDate.format(new Date(propVal), 'yyyy-MM-dd hh:mm:ss');
        }
        return "未知值：" + row[column.property];
    },
    formatCommDatasNotSecond(row, column) {//通用 部分字典值 格式化
        let propName = column.property;
        let propVal = row[column.property];
        if (propVal === null || propVal === '') {
            return;
        }
        if (propName == 'isDel') {
            return propVal == 1 ? '是' : propVal == 0 ? '否' : '未知';
        }
        if (propName == 'failRate' || propName == 'successRate' ) {
            return (propVal == null||propVal == undefined || propVal == "undefined") ? propVal : (propVal*100)+"%" ;
        }
        if (propName == 'isOnline') {
            return propVal == 1 ? '是' : propVal == 0 ? '否' : '未知';
        }
        if (propName == 'resultStatus') {
            return propVal == '1' ? '成功' : propVal == '0' ? '失败' : '未知';
        }
        if (propName == 'operateType') {
            return propVal == 1 ? '查询' : propVal == 2 ? '新增' : propVal == 3 ? '修改' : propVal == 4 ? '删除' : '未知';
        }
        if (propName == 'operateResult') {
            return propVal == '1' ? '成功' : propVal == '0' ? '失败' : '未知';
        }
        if (propName.slice(-propName.length) == propName/*||propName == "auditTime"||propName == 'createTime'||propName == 'modifiedTime'||propName == 'invokTime'*/) {
            return (typeof(propVal) == "undefined" || propVal == undefined || !propVal || propVal == '') ? "" : this.formatDate.format(new Date(propVal), 'yyyy-MM-dd hh:mm');
        }
        return "未知值：" + row[column.property];
    },
    formatDicTionary(rowValue, rowType) {
        let rowName = '';
        var allDictData = JSON.parse(sessionStorage.allDictData);
        if (util.isNotEmpty(allDictData)) {
            allDictData.map(function (x) {
                if (rowType == x.type && rowValue == x.value) {
                    rowName = x.name
                }
            });
            if(util.isNotEmpty(rowName)){
                return rowName;// todo 貌似这里的return 写在循环里边无效
            }
            return rowValue;
        } else {
            util.getAllDictDatas();
            return util.formatDicTionary(rowValue, rowType);
        }
    },
    getAllDictDatas() {
        return util.getDictDatas('',"all")
    },
    getDictDatasByType(value) {
        return util.getDictDatas(value,"type")
    },
    getDictDatasByPid(value) {
        return util.getDictDatas(value,"pid")
    },
    getDictDatas(value,valueType) {
        var allDictData = JSON.parse(sessionStorage.allDictData);
        if (util.isNotEmpty(allDictData)) {
            var someDicDatas = [];
            allDictData.map(function (x) {
                if(valueType=="type"){
                    if (value == x.type) {
                        someDicDatas.push(x);
                    }
                }else if(valueType=="pid"){
                    if (value == x.pid) {
                        someDicDatas.push(x);
                    }
                }else if(valueType=="all"){
                    someDicDatas.push(x);
                }
            });
            return someDicDatas;
        } else {
            // todo 这里可以考虑写成增量的形式 根据type获取字典值，再 push 进 allDictData  等以后有时间了再优化
            // util.refreshDictDatas();
            // return util.getDictDatas(value,valueType)

            var refreshDictionaryListPromise = _ => { return new Promise(function(resolve, reject){
                console.log(" refreshDictDatas start ...  ")
                resolve(util.refreshDictDatas())});
            }
            return refreshDictionaryListPromise().then(res=>{
                console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
                console.log(res)
                console.log(" !!! return === ...  ")
                setTimeout(function (){return util.getDictDatas(value,valueType)},1000);
            }).catch(err=>{
                console.log(err);console.log(" getDictDatas promise err")
            })
        }
    },
    refreshDictDatas(){
        // todo 这里可以考虑写成增量的形式 根据type获取字典值，再 push 进 allDictData  等以后有时间了再优化
        let params = {isPageAble: false,}
        var dictionaryListPromise = _ => { return new Promise(function(resolve, reject){resolve(getDictionaryList(params))}); }
        return dictionaryListPromise().then(res=>{
            sessionStorage.allDictData = JSON.stringify(res.data.data.list) ;
            return res.data.data.list;
        }).catch(err=>{
            console.log(err);console.log("promise err")
        })
    },
    isEmpty(value) {// undefined、null、[]、{}、空字符串及纯空白字符串：''、'    ' 等
        if (value == null) { // 等同于 value === undefined || value === null
            return true;
        }
        var type = Object.prototype.toString.call(value).slice(8, -1);
        switch (type) {
            case 'String':
                return !$.trim(value)||value==''||value==='';
            case 'Array':
                return !value.length||value.length<=0;
            case 'Object':
                return $.isEmptyObject(value); // 普通对象使用 for...in 判断，有 key 即为 false
            default:
                return false; // 其他对象均视作非空
        }
    }
    , isNotEmpty(value) {
        return !(util.isEmpty(value));
    },
    //      =======================api权限管理====================
    apiResourcePermissions(resource){//api资源权限管理 只涉及到当前按钮级
        let bln = false;
        if(!localStorage.apiPermission||localStorage.apiPermission=='[]'||util.isEmpty(JSON.parse(localStorage.apiPermission))){
            return;
        }
        let arr = JSON.parse(localStorage.apiPermission);
        arr.forEach(obj => {
            if(obj.code === resource){
                bln = true;
            }
        });
        return bln;
    },
    apiIsShowEditOrDelete(status,roleId,type){//api资源权限管理 根据审核情况是否显示（编辑/删除）
        let bln = false;
        // 角色是管理员且有权限
        if(roleId === 0) {
            bln = true;
        }else{
            if(type === 'editDel'){
                if(status ===1 || status ===2 || status === 4){
                    bln = true;
                }
            }else if(type === 'resubmit'){
                if(status === 2 || status === 4){
                    bln = true;
                }
            }
        }
        return bln;
    },
    apiIsShowCheck(status,roleId,type){//api资源权限管理 根据审核情况是否显示（审核）
        let bln = false;
        if(roleId === 0){
            if(type === 'pass'){
                if(status === 1 || status ===2){
                    bln = true
                }
            }else if(type === 'noPass'){
                if(status === 1 || status ===2 || status ===4){
                    bln = true
                }
            }
        }
        return bln;
    },

    // 应用市场上传图片的路径
    uploadUrl(){
		return zuulHost+marketManageServer+"/file/upload";
		// return "http://193.112.49.253:8784/m_manage/file/upload";//外网网址
        // return "http://192.168.0.214:8784/m_manage/file/upload";//本地网址
    },
};

sessionStorage.allDictData = util.isEmpty(sessionStorage.allDictData)?sessionStorage.allDictData = '[]':sessionStorage.allDictData;
localStorage.apiPermission = util.isEmpty(localStorage.apiPermission)?localStorage.apiPermission = '[]':localStorage.apiPermission;
export default util;
